package fun.codedesign.jdk.thread;

/**
 * 线程间通讯
 *
 * @author zengjian
 * @create 2018-03-19 20:23
 * @since 1.0.0
 */
public class WaitNotify {

    public static void main(String[] args) throws InterruptedException {
        // wait立即释放锁， 而notify必须执行完成语句块儿后再释放
        Object obj = new Object();
        Thread t1 = new Thread1(obj);
        Thread t2 = new Thread2(obj);
        t1.start();
        Thread.sleep(2000);
        t2.start();
    }

    static class Thread1 extends Thread {
        private Object lock;

        public Thread1(Object lock) {
            this.lock = lock;
        }

        @Override
        public void run() {
            super.run();
            synchronized (lock) {
                System.out.println("thread1");
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("thread1 after");
            }
        }
    }

    static class Thread2 extends Thread {

        private Object obj;

        public Thread2(Object obj) {
            this.obj = obj;
        }

        @Override
        public void run() {
            synchronized (obj) {
                super.run();
                System.out.println("thread2");
                obj.notify();
                System.out.println("thread2 after");
            }
        }
    }
}
